using System.Collections;
using System.Collections.Generic;
using Unity.Burst.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;

public class CloneController : MonoBehaviour
{
    [SerializeField]private float disappearSpeed = 1;
    [SerializeField] private Transform attackCheck;
    [SerializeField] private float attackRadius;
    private SpriteRenderer sr;
    private Animator anim;
    float cloneDuration;
    Color c;
    private Transform closeEnemy;

    private int faceDir = 1;
    private bool canDuplicateClone;
    private float chanceToDuplicate;
    
    private void Awake()
    {
        sr = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();
        StartCoroutine("FaceCloseTarget");
    }

    // Update is called once per frame
    void Update()
    {
        cloneDuration -= Time.deltaTime;
        if (cloneDuration < 0)
        {
            c = sr.color;
            c.a -= Time.deltaTime * disappearSpeed;
            sr.color = c;
            if (c.a <= 0)
            {
                Destroy(gameObject);
            }
        }
    }

    public void SetupClone(float duration,bool canAttack,bool _canDuplicateClone,float _chanceToDuplicate)
    {
        if (canAttack)
        {
            anim.SetInteger("attackNumber", Random.Range(1,3));
        }

        cloneDuration = duration;
        canDuplicateClone = _canDuplicateClone;
        chanceToDuplicate = _chanceToDuplicate;
    }

    private void AnimationTrigger()
    {
        cloneDuration = -.1f;
    }


    private void AttackTrigger()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(attackCheck.position, attackRadius);
        foreach (var collider in colliders)
        {
            EnemyData enemy = collider.GetComponent<EnemyData>();
            if (enemy != null)
            {
                PlayerManager.Instance.Player.data.DoDamage(enemy);
                if (canDuplicateClone)
                {
                    canDuplicateClone = false;
                    if (Random.Range(0, 100) < chanceToDuplicate)
                    {
                        SkillManager.Instance.clone.CreateClone(enemy.transform.position, new Vector3(.8f * faceDir, 0));
                    }
                }
            }
        }
    }

    protected virtual void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(attackCheck.position, attackRadius);
    }

    IEnumerator FaceCloseTarget()
    {
        yield return null;
        closeEnemy = SkillManager.Instance.clone.FindClosestEnemy(transform);

        if (closeEnemy != null)
        {
            if (closeEnemy.transform.position.x < transform.position.x)
            {
                transform.Rotate(0, 180, 0);
                faceDir = -1;
            }
        }

    }

    
}

